package com.ruoyi.system.service.impl.transport;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.common.CargoStateConstant;
import com.ruoyi.system.common.CompanyTypeConstant;
import com.ruoyi.system.common.TransportCompanyType;
import com.ruoyi.system.domain.db.basic.BasicCompanies;
import com.ruoyi.system.domain.db.basic.BasicVehicles;
import com.ruoyi.system.domain.db.basic.BasicWarehouses;
import com.ruoyi.system.domain.db.transport.TransportTask;
import com.ruoyi.system.domain.db.warehousestate.OrderWarehouseState;
import com.ruoyi.system.domain.dto.TradeCargoOrderDto;
import com.ruoyi.system.domain.dto.TransportExternalDto;
import com.ruoyi.system.domain.dto.TransportTaskDto;
import com.ruoyi.system.domain.request.TradeCargoOrderDeliveryRequest;

import com.ruoyi.system.domain.vo.TransportTaskVo;
import com.ruoyi.system.mapper.basic.BasicCompaniesMapper;
import com.ruoyi.system.mapper.basic.BasicVehiclesMapper;
import com.ruoyi.system.mapper.basic.BasicWarehousesMapper;
import com.ruoyi.system.mapper.trade.TradeCargoOrderMapper;
import com.ruoyi.system.mapper.transport.TransportTaskMapper;
import com.ruoyi.system.mapper.warehousestate.OrderWarehouseStateMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.system.service.ITransportTaskService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 运输任务Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-08-03
 */
@Service
public class TransportTaskServiceImpl implements ITransportTaskService 
{
    @Autowired
    private TransportTaskMapper transportTaskMapper;

    @Autowired
    private BasicWarehousesMapper basicWarehousesMapper;

    @Autowired
    private TradeCargoOrderMapper tradeCargoOrderMapper;

    @Resource
    private BasicVehiclesMapper basicVehiclesMapper;

    @Resource
    private BasicCompaniesMapper basicCompaniesMapper;


    /**
     * 查询运输任务
     * 
     * @param taskId 运输任务主键
     * @return 运输任务
     */
    @Override
    @Transactional
    public TransportTaskVo selectTransportTaskByTaskId(Long taskId)
    {
        TransportTaskDto transportTaskDto = transportTaskMapper.selectTransportTaskByTaskId(taskId);
        List<BasicWarehouses> basicWarehouses = basicWarehousesMapper.selectBasicWarehouses(null);
        TransportTaskVo transportTaskVo = convertToVO(transportTaskDto);
        transportTaskVo.setWarehouses(basicWarehouses);
        transportTaskVo.setOrders(tradeCargoOrderMapper.selectCargoInfoByTaskId(taskId));
        if(transportTaskVo.getType() == TransportCompanyType.INTERNAL) {
            BasicVehicles basicVehicles = basicVehiclesMapper.selectInternalVehicleByTaskId(transportTaskVo.getTaskId());
            transportTaskVo.setVehicle(basicVehicles);
        }else {
            TransportExternalDto transportExternalDto = basicVehiclesMapper.selectExternalVehicleByTaskId(transportTaskVo.getTaskId());
            transportTaskVo.setVehicle(transportExternalDto);
        }
        return transportTaskVo;
    }

    /**
     * 查询运输任务列表
     *
     * @param transportTask 运输任务
     * @return 运输任务
     */
    @Override
    public List<TransportTaskVo> selectTransportTaskList(TransportTask transportTask)
    {
        transportTask.setManagerId(SecurityUtils.getUserId());
        List<TransportTaskDto> transportTaskDtos = transportTaskMapper.selectTransportTaskList(transportTask);
        List<TransportTaskVo> collect = transportTaskDtos.stream().map(TransportTaskServiceImpl::convertToVO).collect(Collectors.toList());
        return collect;
    }

    /**
     * 新增运输任务
     * 
     * @param transportTask 运输任务
     * @return 结果
     */
    @Override
    public int insertTransportTask(TransportTask transportTask)
    {
        Long userId = SecurityUtils.getUserId();
        Date nowDate = DateUtils.getNowDate();
        transportTask.setCreateTime(nowDate);
        transportTask.setUpdateTime(nowDate);
        transportTask.setCreateBy(userId);
        transportTask.setUpdateBy(userId);
        transportTask.setManagerId(userId);
        return transportTaskMapper.insertTransportTask(transportTask);
    }

    /**
     * 修改运输任务
     * 
     * @param transportTask 运输任务
     * @return 结果
     */
    @Override
    public int updateTransportTask(TransportTask transportTask)
    {
        Long userId = SecurityUtils.getUserId();
        Date nowDate = DateUtils.getNowDate();
        transportTask.setUpdateTime(nowDate);
        transportTask.setUpdateBy(userId);
        return transportTaskMapper.updateTransportTask(transportTask);
    }

    /**
     * 批量删除运输任务
     * 
     * @param taskIds 需要删除的运输任务主键
     * @return 结果
     */
    @Override
    public int deleteTransportTaskByTaskIds(Long[] taskIds)
    {
        return transportTaskMapper.deleteTransportTaskByTaskIds(taskIds);
    }

    /**
     * 删除运输任务信息
     * 
     * @param taskId 运输任务主键
     * @return 结果
     */
    @Override
    public int deleteTransportTaskByTaskId(Long taskId)
    {
        return transportTaskMapper.deleteTransportTaskByTaskId(taskId);
    }

    /**
     * 查询没有被分配的订单
     *
     * @return
     */
    @Override
    public List<TradeCargoOrderDto> selectUndeliveriedOrderList() {
        return tradeCargoOrderMapper.selectUnDeliveriedCargoOrderList();
    }

    /**
     * 为运输任务分配订单
     * @param tradeCargoOrderDeliveryRequest 订单分配请求
     * @return 结果
     */
    @Override
    @Transactional
    public int assignOrderToTask(TradeCargoOrderDeliveryRequest tradeCargoOrderDeliveryRequest) {

        // 获取任务信息
        TransportTaskDto transportTaskDto = transportTaskMapper.selectTransportTaskByTaskId(tradeCargoOrderDeliveryRequest.getTaskId());
        Date nowDate = DateUtils.getNowDate();
        Long userId = SecurityUtils.getUserId();
        // 查看是否是以及分配过订单
        if(Objects.equals(transportTaskDto.getState(), CargoStateConstant.RECEIVED)){
            // 将已经分配的订单状态改为未分配
            tradeCargoOrderMapper.updateTradeCargoOrderStateByTaskId(tradeCargoOrderDeliveryRequest.getTaskId(), CargoStateConstant.WAITING, nowDate);
            // 删除Package已经分配的订单
            transportTaskMapper.deleteTransportOrderByTaskId(tradeCargoOrderDeliveryRequest.getTaskId());
            if(Objects.equals(transportTaskDto.getType(), TransportCompanyType.INTERNAL)) {
                // 内部
                transportTaskMapper.deleteInternalTransportCarByTaskId(tradeCargoOrderDeliveryRequest.getTaskId());
            }else {
                // 外部
                transportTaskMapper.deleteExternalTransportCarByTaskId(tradeCargoOrderDeliveryRequest.getTaskId());
            }
        }
        // 加入运输任务表
        transportTaskMapper.assignTransportTask(tradeCargoOrderDeliveryRequest);
        // 更新订单状态
        tradeCargoOrderMapper.updateTradeCargoOrderStateByTaskId(tradeCargoOrderDeliveryRequest.getTaskId(), CargoStateConstant.RECEIVED, nowDate);
        // 根据运输类型分配运输车
        if(Objects.equals(transportTaskDto.getType(), TransportCompanyType.INTERNAL)) {
            // 内部
            transportTaskMapper.assignInternalTransportCar(tradeCargoOrderDeliveryRequest.getTaskId(), tradeCargoOrderDeliveryRequest.getVehicleId());
        }else {
            // 外部
            transportTaskMapper.assignExternalTransportCar(tradeCargoOrderDeliveryRequest);
        }
        // 更新运输任务状态
        transportTaskMapper.updateTransportTask(new TransportTask() {{
            setTaskId(tradeCargoOrderDeliveryRequest.getTaskId());
            setState(CargoStateConstant.RECEIVED);
            setUpdateBy(userId);
            setUpdateTime(nowDate);
        }});
        return 1;
    }

    @Override
    public List<BasicWarehouses> getWarehouseList() {
        return basicWarehousesMapper.selectBasicWarehouses(null);
    }

    /**
     * 返回可用汽车列表
     */
    @Override
    public List<BasicVehicles> getAvailableCarList() {
        // 获取没有在运输的车辆
        return basicVehiclesMapper.selectUnDeliveringVehicleList();
    }

    /**
     * 返回运输公司列表
     */
    @Override
    public List<BasicCompanies> getTransportCompanyList() {
        BasicCompanies basicCompanies = new BasicCompanies();
        basicCompanies.setCompanyType(CompanyTypeConstant.TRANSPORT);
        return basicCompaniesMapper.selectBasicCompaniesList(basicCompanies);
    }

    public static TransportTaskVo convertToVO(TransportTaskDto dto) {
        TransportTaskVo vo = new TransportTaskVo();
        vo.setTaskId(dto.getTaskId());
        vo.setType(dto.getType());
        vo.setWeight(dto.getWeight());
        vo.setState(dto.getState());
        vo.setCreateTime(dto.getCreateTime());
        vo.setUpdateTime(dto.getUpdateTime());
        vo.setUserId(dto.getManager().getUserId());
        vo.setUserName(dto.getManager().getUserName());
        vo.setDepartureId(dto.getDeparture().getWarehouseId());
        vo.setDepartureWarehouseName(dto.getDeparture().getWarehouseName());
        vo.setDepartureAddress(dto.getDeparture().getAddress());
        vo.setDepartureDistrict(dto.getDeparture().getDistrict());
        vo.setDepartureTown(dto.getDeparture().getTown());
        vo.setDepartureLevel(dto.getDeparture().getLevel());
        vo.setDestinationId(dto.getDestination().getWarehouseId());
        vo.setDestinationWarehouseName(dto.getDestination().getWarehouseName());
        vo.setDestinationAddress(dto.getDestination().getAddress());
        vo.setDestinationDistrict(dto.getDestination().getDistrict());
        vo.setDestinationTown(dto.getDestination().getTown());
        vo.setDestinationLevel(dto.getDestination().getLevel());
        return vo;
    }



}
